<template>
  <div style="max-width: 500px; margin: 0 auto;">
    <h2>发布新闻稿</h2>
    <el-form :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入新闻标题" />
      </el-form-item>
      <el-form-item label="内容">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          placeholder="请输入新闻内容"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitNews">发布</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const orgId = localStorage.getItem('loginId')
const form = ref({
  title: '',
  content: ''
})

const submitNews = async () => {
  if (!form.value.title || !form.value.content) {
    ElMessage.error('请填写标题和内容')
    return
  }
  try {
    const res = await axios.post(
      `http://localhost:8080/orgs/${orgId}/announcements`,
      {
        "title": form.value.title,
        "orgId": Number(orgId),
        "content": form.value.content
      }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('新闻稿发布成功')
      resetForm()
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '发布失败')
    }
  } catch (e) {
    ElMessage.error('发布失败')
  }
}

const resetForm = () => {
  form.value.title = ''
  form.value.content = ''
}
</script>